const configCenter = require("uni-config-center");
const crypto = require("crypto");
const config = configCenter({
	pluginId: 'vk-unicloud'
}).requireFile('index.js');

function objKeySort(arys, partner_key) {
	//先用Object内置类的keys方法获取要排序对象的属性名数组，再利用Array的sort方法进行排序 
	var newkey = Object.keys(arys).sort();
	console.log('newkey=' + newkey);
	var newObj = '';
	//建立一个新的对象，用于存放排好序的键值对 
	for (var i = 0; i < newkey.length; i++) { //遍历newkey数组 
		newObj += [newkey[i]] + '=' + arys[newkey[i]] + '&';
	}
	return newObj.substring(0, newObj.length - 1) + '&partner_key=' + partner_key;
}
module.exports = {
	/**
	 * 添加单条数据
	 * @url admin/kong/sys/add 前端调用的url参数地址
	 * data 请求参数 说明
	 * res 返回参数说明
	 * @param {Number} code 错误码，0表示成功
	 * @param {String} msg 详细信息
	 */
	main: async (event) => {
		let {
			data = {}, userInfo, util, filterResponse, originalParam
		} = event;
		let {
			customUtil,
			uniID,
			config,
			pubFun,
			vk,
			db,
			_
		} = util;
		let {
			uid
		} = data;
		let res = {
			code: 0,
			msg: 'ok'
		};
		const {
			baijiayun
		} = config.vk;
		console.log(config)
		// 业务逻辑开始-----------------------------------------------------------
		let {
			room_id,
			user_number,
			user_role,
			user_name,
			user_avatar
		} = data;
		let baijiayunParmas = {
			room_id,
			user_number,
			user_role,
			user_name,
			user_avatar
		}
		let private_domain = baijiayun.private_domain
		let str = objKeySort(baijiayunParmas, baijiayun.Partner_Key)
		console.log(str)
		let sign = crypto
			.createHash('md5')
			.update(str, 'utf-8')
			.digest('hex').toLowerCase()

		let url =
			`https://${private_domain}.at.baijiayun.com/web/room/enter?room_id=${room_id}&user_number=${user_number}&user_name=${user_name}&user_role=${user_role}&user_avatar=${user_avatar}&sign=${sign}`

		res.data = url

		// 业务逻辑结束-----------------------------------------------------------
		return res;
	}
}
